package com.api.util;

import com.api.entity.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.Date;
import java.util.Random;

/*
    @ClassName JwtUtil
    @Description TODO
    @Date 2021/8/31、10:42
*/
@ConfigurationProperties("jwt.com.api.config")
public class JwtUtil {
    //盐
    private String key = getRandomString(4);
    //过期时间
    private long ttl = 50000;

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }


    /**
     * 生成JWT
     * @param id 用户id
     * @param subject 用户信息
     * @param user 自定义key-value 角色
     * @return
     */
    public String createJWT(String id, String subject, User user) {
        //signWith(SignatureAlgorithm.HS256, key) 设置加密方式，和盐 。盐自己规定
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key)
                .claim("roles", user);
        if (ttl > 0) {
            //设置过期时间
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr){
        return  Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

    /*
     * @Author: XiaoDun
     * @Description:随机生成盐
     * @Date: 2021/8/31 11:43
     * params
     * return java.lang.String
     **/
    public static String getRandomString(int length){
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for(int i = 0;i < length ; i++){
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }
}
